<template>
  <div class="profile-container">
    <el-card class="profile-card">
      <template #header>
        <div class="card-header">
          <h2>个人中心</h2>
        </div>
      </template>

      <el-row :gutter="20">
        <el-col :span="8">
          <div class="avatar-container">
            <el-avatar :size="120" :src="userInfo.avatarUrl || 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'" />
            <el-upload class="avatar-uploader" action="#" :http-request="handleAvatarUpload" :show-file-list="false" :before-upload="beforeAvatarUpload">
              <el-button type="primary" size="small" class="upload-btn">更换头像</el-button>
            </el-upload>
          </div>
        </el-col>

        <el-col :span="16">
          <div class="info-container">
            <el-descriptions :column="1" border>
              <el-descriptions-item label="学号">{{ userInfo.username || userInfo.stuId }}</el-descriptions-item>
              <el-descriptions-item label="姓名">{{ userInfo.name }}</el-descriptions-item>
              <el-descriptions-item label="性别">{{ userInfo.gender || '未设置' }}</el-descriptions-item>
              <el-descriptions-item label="身份">学生</el-descriptions-item>
              <el-descriptions-item label="登录时间">{{ loginTime }}</el-descriptions-item>
            </el-descriptions>

            <el-button type="primary" @click="passwordDialogVisible = true" class="change-pwd-btn">
              修改密码
            </el-button>
          </div>
        </el-col>
      </el-row>
    </el-card>

    <!-- 修改密码对话框 -->
    <el-dialog title="修改密码" v-model="passwordDialogVisible" width="400px">
      <el-form :model="passwordForm" :rules="passwordRules" ref="passwordFormRef" label-width="100px">
        <el-form-item label="原密码" prop="oldPassword">
          <el-input v-model="passwordForm.oldPassword" type="password" show-password />
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input v-model="passwordForm.newPassword" type="password" show-password />
        </el-form-item>
        <el-form-item label="确认新密码" prop="confirmPassword">
          <el-input v-model="passwordForm.confirmPassword" type="password" show-password />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="passwordDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleChangePassword" :loading="changingPassword">
            确认修改
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getUserInfo, getToken, updateUserInfo } from '@/utils/auth'
import { changePassword } from '@/api/user'
import { uploadAvatar } from '@/api/upload'
import { useRouter } from 'vue-router'
import { formatDate } from '@/utils/format'

const router = useRouter()

// 用户信息
const userInfo = ref({
  username: '',
  name: '',
  gender: '',
  type: 'student',
  avatarUrl: ''
})

// 登录时间
const loginTime = computed(() => {
  // 从localStorage获取登录时间，如果没有则使用当前时间
  const loginTimeStr = localStorage.getItem('loginTime')
  const time = loginTimeStr ? new Date(parseInt(loginTimeStr)) : new Date()
  return formatDate(time, 'YYYY-MM-DD HH:mm:ss')
})

// 获取本地存储的用户信息
onMounted(async () => {
  // 先使用本地存储的用户信息
  userInfo.value = getUserInfo() || {}

  // 尝试获取最新用户信息
  await updateUserInfo()
  // 重新获取最新的用户信息
  userInfo.value = getUserInfo() || {}

  // 如果没有登录时间，设置当前时间
  if (!localStorage.getItem('loginTime')) {
    localStorage.setItem('loginTime', Date.now().toString())
  }

  // 如果是测试环境并且没有性别信息，添加模拟数据
  if (import.meta.env.DEV && !userInfo.value.gender) {
    userInfo.value.gender = '男'
  }
})

// 头像上传相关
const handleAvatarUpload = async (options) => {
  const { file } = options
  const formData = new FormData()
  formData.append('file', file)

  try {
    // 在开发环境中模拟头像上传
    if (import.meta.env.DEV && import.meta.env.VITE_USE_MOCK === 'true') {
      // 模拟网络请求延迟
      await new Promise(resolve => setTimeout(resolve, 1000))

      // 创建临时URL作为上传后的头像URL
      const avatarUrl = URL.createObjectURL(file)

      // 更新用户信息
      userInfo.value.avatarUrl = avatarUrl

      // 更新本地存储的用户信息
      const storedUserInfo = getUserInfo()
      if (storedUserInfo) {
        storedUserInfo.avatarUrl = avatarUrl
        localStorage.setItem('userInfo', JSON.stringify(storedUserInfo))
      }

      ElMessage.success('头像上传成功')
      return
    }

    // 使用API上传头像
    ElMessage.info('正在上传头像...')
    const res = await uploadAvatar(formData)

    if (!res.data || !res.data.url) {
      throw new Error('上传失败，未获取到有效的头像URL')
    }

    // 上传成功后，从服务器获取最新的用户信息
    await updateUserInfo()
    // 刷新页面用户信息
    userInfo.value = getUserInfo() || {}

    ElMessage.success('头像上传成功')
  } catch (error) {
    ElMessage.error(error.message || '头像上传失败，请稍后重试')
  }
}

const beforeAvatarUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('上传头像图片只能是图片格式!')
  }

  if (!isLt2M) {
    ElMessage.error('上传头像图片大小不能超过 2MB!')
  }

  return isImage && isLt2M
}

// 修改密码相关
const passwordDialogVisible = ref(false)
const passwordFormRef = ref(null)
const changingPassword = ref(false)

const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

const validateConfirmPassword = (rule, value, callback) => {
  if (value !== passwordForm.newPassword) {
    callback(new Error('两次输入密码不一致'))
  } else {
    callback()
  }
}

const passwordRules = {
  oldPassword: [
    { required: true, message: '请输入原密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能小于6个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入新密码', trigger: 'blur' },
    { validator: validateConfirmPassword, trigger: 'blur' }
  ]
}

const handleChangePassword = () => {
  passwordFormRef.value.validate(async (valid) => {
    if (!valid) return

    changingPassword.value = true

    try {
      // 在开发环境中模拟密码修改
      if (import.meta.env.DEV) {
        // 模拟网络请求延迟
        await new Promise(resolve => setTimeout(resolve, 1000))

        // 密码强度检查 - 模拟密码太简单的情况
        if (passwordForm.newPassword === '123456') {
          throw new Error('密码过于简单，请设置更复杂的密码')
        }

        ElMessage.success('密码修改成功，请重新登录')

        // 模拟清除登录信息并跳转到登录页
        setTimeout(() => {
          // 清除token和用户信息
          localStorage.removeItem('token')
          localStorage.removeItem('userInfo')
          // 跳转到登录页
          router.push('/')
        }, 1500) // 延迟1.5秒，让用户看到成功提示

        return
      }

      // 生产环境下使用真实API
      await changePassword({
        oldPassword: passwordForm.oldPassword,
        newPassword: passwordForm.newPassword
      })

      ElMessage.success('密码修改成功，请重新登录')

      // 密码修改成功后，清除登录信息并跳转到登录页
      setTimeout(() => {
        // 清除token和用户信息
        localStorage.removeItem('token')
        localStorage.removeItem('userInfo')
        // 跳转到登录页
        router.push('/')
      }, 1500) // 延迟1.5秒，让用户看到成功提示

    } catch (error) {
      // 显示错误信息
      if (error.message && (error.message.includes('JWT') || error.message.includes('token'))) {
        ElMessageBox.confirm(
          '您的登录已过期，需要重新登录',
          '会话过期',
          {
            confirmButtonText: '重新登录',
            cancelButtonText: '取消',
            type: 'warning'
          }
        ).then(() => {
          // 清除token和用户信息
          localStorage.removeItem('token')
          localStorage.removeItem('userInfo')
          // 跳转到登录页
          router.push('/')
        }).catch(() => { })
      } else {
        ElMessage.error(error.message || '密码修改失败，请稍后重试')
      }
    } finally {
      changingPassword.value = false
      passwordDialogVisible.value = false
      // 重置表单
      passwordForm.oldPassword = ''
      passwordForm.newPassword = ''
      passwordForm.confirmPassword = ''
    }
  })
}
</script>

<style scoped>
.profile-container {
  padding: 20px;
}

.profile-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.avatar-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;
}

.upload-btn {
  margin-top: 15px;
}

.info-container {
  padding: 20px;
}

.change-pwd-btn {
  margin-top: 20px;
}
</style>